import React, { useState, useEffect, useLayoutEffect } from 'react';
import { Alert, TextInput, onPress, Button, View, Text, FlatList, Image, Switch, StyleSheet, SafeAreaView, Pressable, ScrollView } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';
import * as ImagePicker from 'expo-image-picker';
import * as FileSystem from 'expo-file-system';
function MyIfomation() {
    const navigation = useNavigation(); // 获取navigation对象
    const [userInfo, setUserInfo] = useState({});
    const [image, setImage] = useState(null);
    const [username, setUsername] = useState('原始昵称');
    const changeUsername = () => {

    };
    const convertImageToBase64 = async (imageUri) => {
        try {
            const base64Data = await FileSystem.readAsStringAsync(imageUri, {
                encoding: FileSystem.EncodingType.Base64,
            });
            return base64Data;
        } catch (error) {
            console.error(error);
        }
    }
    const pickImage = async () => {
        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.Images,
            allowsEditing: true,
            aspect: [4, 4],
            quality: 1,
        });

        console.log(result.assets[0]);

        // 检查图片是否是Base64格式
        if (!/^data:image\/[a-zA-Z]*;base64,/.test(result.assets[0].uri)) {
            convertImageToBase64(result.assets[0].uri)
                .then(base64Data => {
                    console.log('Image (base64): ', base64Data);
                    setImage("data:image/jpg;base64," + base64Data);
                })
                .catch(err => {
                    console.error('Error converting image to base64', err);
                });
        } else {
            setImage(result.assets[0].uri);
        }
    };
    useEffect(() => {
        if (image) {
            axios.post('http://47.111.227.58:3000/users/changUserImg', {
                data: {
                    id: userInfo.id,
                    imgUrl: image
                }
            })
                .then(response => {
                    console.log(response.data);
                    userInfo.imgUrl = image
                    AsyncStorage.setItem('userInfo', JSON.stringify(userInfo));
                })
                .catch(error => {
                    console.error(error);
                });
        }
    }, [image]);

    useEffect(() => {
        (async () => {
            const userinfo = await AsyncStorage.getItem('userInfo');
            if (userinfo) {
                setUserInfo(JSON.parse(userinfo));
                setImage(JSON.parse(userinfo).imgUrl);
            }
            const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
            if (status !== 'granted') {
                console.log('拒绝访问图片库权限！');
            }
            // console.log(userinfo)
        })();
    }, []);
    // useEffect(() => {
    //     (async () => {
    //         if (userInfo) {
    //             const userinfo = await AsyncStorage.getItem('userInfo');
    //             if (userinfo) {
    //                 setUserInfo(JSON.parse(userinfo));
    //                 setImage(JSON.parse(userinfo).imgUrl);
    //             }
    //         }
    //     })();
    // }, [userInfo]);
    return (

        <View style={styles.container}>

            <ScrollView>


                <View style={styles.menuContainer}>
                    {/* //头像 */}
                    <Pressable onPress={pickImage}>
                        <MenuItem text="头像" icon={image} isPhoto={true} />
                    </Pressable>
                    <Pressable onPress={() => navigation.navigate('修改昵称')}>
                        <MenuItem text="昵称" extraText={userInfo.username} />
                    </Pressable>
                    <MenuItem text="学校" extraText="浙大城市学院" />
                    <MenuItem text="手机号" extraText="已绑定" />
                    <MenuItem text="校园认证" extraText="已认证" />
                    <MenuItem text="数字ID" extraText="32101098" isLastItem={true} />

                </View>
                <View style={styles.menuContainer}>
                    <MenuItem text="修改个人资料卡片" />
                    <MenuItem text="展示个人信息" switch={true} hintText="开启后你的头像卡片中将展示年龄和家乡信息" />
                    <MenuItem text="展示会员标识" switch={true} hintText="关闭后，会员标识将不会对外展示" />
                    <MenuItem text="个人主页展示ID" switch={true} hintText="ID可用于赠送会员，关闭后，个人主页将隐藏ID" isLastItem={true} />
                </View>


            </ScrollView >

        </View >
    );
}


function MenuItem({ text, icon, hintText, extraText, isLastItem, switch: showSwitch }) {
    const [isEnabled, setIsEnabled] = React.useState(false);
    const toggleSwitch = () => setIsEnabled(previousState => !previousState);

    return (

        <View style={[styles.menuItem, isLastItem && styles.lastItem]}>

            {/* <Text style={styles.menuText}>{text}</Text> */}

            <View style={styles.textContainer}>
                <Text style={styles.menuText}>{text}</Text>

                {hintText && <Text style={styles.hintText}>{hintText}</Text>}
            </View>
            {extraText && <Text style={styles.smallText}>{extraText}</Text>}

            {icon && <Image style={styles.menuIcon} source={{ uri: icon }} />}

            {showSwitch ? (
                <Switch
                    trackColor={{ false: "#767577", true: "#EB7A76" }}
                    thumbColor={isEnabled ? "#fff" : "#f4f3f4"}
                    onValueChange={toggleSwitch}
                    value={isEnabled}
                />
            ) : (
                <Image style={styles.arrowIcon} source={require('../assets/jiantou.jpg')} />
            )}

        </View>
    );
}



const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f0f0f0',//#f0f0f0

    },
    menuContainer: {
        borderWidth: 1,
        borderColor: '#ffffff',
        // borderRadius: 10,
        padding: 8,
        marginVertical: 3,
        backgroundColor: '#ffffff',
        // margin: 10,
        marginTop: 3,
    },
    menuItem: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingVertical: 10,
        borderBottomWidth: 1,
        borderBottomColor: '#EFEFEF',
    },
    textContainer: {
        flex: 1,
    },

    menuText: {
        flex: 1,
        fontSize: 16,
        fontWeight: 'bold',

    },
    smallText: {
        fontSize: 12, // 小字的字体大小
        color: 'grey', // 小字的颜色
        marginRight: 0, // 小字与箭头的距离
    },
    menuIcon: {
        width: 50,
        height: 50,
        marginRight: 2,
        //alignSelf: 'flex-end',
    },
    arrowIcon: {
        width: 16,
        height: 16,
    },
    lastItem: {
        borderBottomWidth: 0, // 移除底部边框
    },
    hintText: {
        fontSize: 12, // 提示文本的字体大小
        color: '#6e6e6e', // 提示文本的颜色
        marginTop: 1, // 提示文本与主文字的上边距
    },

});

export default MyIfomation;
